package com.ruoyi.system.service.impl;


import com.ruoyi.common.utils.FileUpLoadUtil;
import com.ruoyi.system.domain.SysGameRecord;
import com.ruoyi.system.domain.member_info;
import com.ruoyi.system.mapper.SysCompetitionMapper;
import com.ruoyi.system.service.ISysGameRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author kaka.huang
 * @for study
 */
@Service
public class ISysGameRecordServiceImpl implements ISysGameRecordService {
    @Autowired
    SysCompetitionMapper sysCompetitionMapper;

    @Autowired
    FileUpLoadUtil fileUpLoadUtil;

    @Override
    public Map<String, Object> selectCompetition(int pageNum, int pageSize, String postCode, String postName, String status) {
        int offset = (pageNum - 1) * pageSize;

        List<SysGameRecord> resultCompetitions = sysCompetitionMapper.selectCompetitionMapper(postCode, postName, status);
        System.out.println(resultCompetitions);
        // 第一步：根据 game_id 分组得出总数量 total
        long totalGameIdCount = resultCompetitions.stream()
                .map(SysGameRecord::getGame_id)
                .distinct()
                .count();

        // 第二步：按照 game_id 分组，并将 name 整合
        Map<String, SysGameRecord> groupedCompetitions = new HashMap<>();

        for (SysGameRecord competition : resultCompetitions) {
            String gameId = competition.getGame_id();
            if (groupedCompetitions.containsKey(gameId)) {
                SysGameRecord existingCompetition = groupedCompetitions.get(gameId);
                String mergedNames = existingCompetition.getName() + "、" + competition.getName();
                existingCompetition.setName(mergedNames);

            } else {
                groupedCompetitions.put(gameId, new SysGameRecord(
                        competition.getGame_id(),
                        competition.getGame_time(),
                        competition.getName(),
                        competition.getGame_name(),
                        competition.getGame_result(),
                        competition.getCertificate(),
                        competition.getTop()
                ));
            }
        }

        System.out.println(groupedCompetitions);

        // 将分组后的数据转换为列表
        List<SysGameRecord> groupedCompetitionsList = new ArrayList<>(groupedCompetitions.values());

        // 第三步：筛出 top 不为空的数据并按照升序排列，然后将 top 为空的数据放在后面
        List<SysGameRecord> sortedCompetitions = groupedCompetitionsList.stream()
                .sorted(Comparator.comparing(SysGameRecord::getTop, Comparator.nullsLast(Comparator.naturalOrder())))
                .collect(Collectors.toList());

        // 分页处理
        List<SysGameRecord> paginatedCompetitions = sortedCompetitions.stream()
                .skip(offset)
                .limit(pageSize)
                .collect(Collectors.toList());

        // 查询种类
        List<String> kinds = sysCompetitionMapper.selectAllResultKind();
        // 构建返回的 Map
        Map<String, Object> result = new HashMap<>();
        result.put("competitions", paginatedCompetitions);
        result.put("total", totalGameIdCount);
        result.put("kinds", kinds);
        return result;
    }

    @Override
    public List<member_info> selectMemberInfo(String searchName) {
        List<member_info> memberInfos = sysCompetitionMapper.selectMemberInfo(searchName);
        return memberInfos;
    }

    //    新增字段方法
    @Override
    @Transactional
    public String addCompetition(String game_name, String[] team, String game_time, String game_result, Integer top) {

        // 1. 生成UUID作为game_id
        String game_id = UUID.randomUUID().toString();

        // 2. 将game_id, game_name, game_time, game_result, top存入game_record表中
        sysCompetitionMapper.insertGameRecord(game_id, game_name, game_time, game_result, top);

        // 3. 将game_id与team中的多条member_id存入game_meb_mapping表中
        for (String member_id : team) {
            String game_meb_mapping_id = UUID.randomUUID().toString();
            sysCompetitionMapper.insertGameMebMapping(game_meb_mapping_id, game_id, member_id);
        }

        // 操作成功
        return game_id;
    }

//    证书提交接口

    @Override
    @Transactional
    public String submitPic(String game_id, MultipartFile image , String certificate) {
        System.out.println("图片接收");

        if (image == null || image.isEmpty()) {
            throw new IllegalArgumentException("图片不能为空");
        }

        try (InputStream inputStream = image.getInputStream()) {
            // 读取图片的字节数据
            byte[] fileBytes = inputStream.readAllBytes();

            // 调用上传方法
            String NewName = fileUpLoadUtil.uploadFileToOSS(fileBytes, game_id ,certificate);

            // 更新数据库
            sysCompetitionMapper.updateCertificate(NewName, game_id);

            return null;

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("图片上传失败: " + e.getMessage(), e);
        }
    }

    //  修改表接口
    @Override
    @Transactional
    public String UpdateCom(String game_id, String game_name, String[] team, String game_time, String game_result, Integer top) {
//        1.修改game_record表
        sysCompetitionMapper.UpdateGameRecord(game_id, game_name, game_time, game_result, top);
//        2.若team数组为空 就不做任何操作
        //        3.若team数组不为空，就根据game_id与team中的member_id更新mapping表
//        4.为了便捷，直接根据game_id删除所有数据，再重新插入
        if (team != null) {
            sysCompetitionMapper.DeleteMapping(game_id);
            for (int i = 0; i < team.length; i++) {
                String game_meb_mapping_id = UUID.randomUUID().toString();
                sysCompetitionMapper.insertGameMebMapping(game_meb_mapping_id, game_id, team[i]);
            }
        }
        return null;
    }

//    删除
    @Override
    @Transactional
    public String remove(String game_id) {
        sysCompetitionMapper.DeleteMapping(game_id);
        sysCompetitionMapper.DeleteGameRecord(game_id);
        return null;
    }
}
